<template>
  <div style="width: 100vw; height: 100vh">
    <!-- <div style="padding: 20px">
      <el-alert
        title="无法从请求头获取Client_Id"
        :closable="false"
        type="error"
      />
    </div> -->
  </div>
</template>
<script lang="ts" setup name="Authorize">
import { generateCodeVerifier, generateCodeChallenge } from "@/utils/pkce.ts";
import { onMounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useCodeVerifierStore } from "@/store/code-verifier";
const router = useRouter();
const route = useRoute();
const codeVerifierStore = useCodeVerifierStore();
const clientId = ref(import.meta.env.VITE_CLIENT_ID);
const redirectUri = ref(
  window.location.origin + router.resolve({ path: "/callback" }).href
);
const codeVerifier = ref("");
onMounted(async () => {
  if (route.query && route.query.client_id) {
    clientId.value = route.query.client_id as string;
  }
  if (route.query && route.query.redirect_uri) {
    redirectUri.value = route.query.redirect_uri as string;
  }
  if (route.query && route.query.code_verifier) {
    codeVerifier.value = route.query.code_verifier as string;
  } else {
    codeVerifier.value = await generateCodeVerifier();
  }
  goAuthorize();
});

const goAuthorize = async () => {
  const codeChallenge = await generateCodeChallenge(codeVerifier.value);
  // 生成随机state值（防CSRF）
  const state = Math.random().toString(36).substring(2);
  codeVerifierStore.setCodeVerifier(codeVerifier.value);
  codeVerifierStore.setState(state);
  // 构造授权URL
  const authUrl =
    `${import.meta.env.VITE_API_BASE_URL}/connect/authorize?` +
    `response_type=code` +
    `&client_id=${clientId.value}` +
    `&redirect_uri=${encodeURIComponent(redirectUri.value)}` +
     `&scope=openid profile offline_access` +
     `&prompt=login` +
    `&state=${state}` +
    `&code_challenge=${codeChallenge}` +
    // `&code_verifier=${codeVerifier.value}` +
    `&code_challenge_method=S256`;

  window.location.href = authUrl;
};
</script>
<style lang="scss" scoped></style>
